/**
 * =========================== 七牛通用上传方法 ===========================
 */

function getSingleName(srcName) {
	var single = md5(Number(Math.random().toString().substr(3, 5) + Date.now()).toString());
	var name = single + "." + getFileSuffix(srcName);
	return name;
}

var subscription = null;

function cancelUpload() {
	subscription.unsubscribe() // 上传取消
}

/**上传成功后返回上传成功图片的key值（唯一键）*/
function uploadSingleFile(file, token, onUploadSuccess, onUploadProgress, onUploadError) {
	let config = {
		useCdnDomain: true,
		// region: qiniu.region.z2
		region: null, //region: 选择上传域名区域；当为 null 或 undefined 时，自动分析上传域名区域
		retryCount: 3, //重试次数
	};
	let putExtra = {
		fname: "",
		params: {},
		mimeType: null
	};

	let params = {};
	ApiUtil.post(HTTP.getQiniuToken, token, params, true, false, function(res) {
		var token = res.data;
		var newName = getSingleName(file.name);

		var observer = {
			next(res) {
				let total = res.total;
				console.log("进度：" + total.percent + "% ");
				if (onUploadProgress) {
					onUploadProgress(total.percent);
				}
			},
			error(err) {
				if (onUploadError) {
					onUploadError("上传失败");
				}
			},
			complete(res) {
				console.log("上传结束上传文件名为:" + res.key);
				if (onUploadSuccess) {
					onUploadSuccess(res.key);
				}
			}
		}

		var observable = qiniu.upload(file, newName, token, putExtra, config)
		var subscription = observable.subscribe(observer) // 上传开始
		// var subscription = observable.subscribe(next, error, complete) // 这样传参形式也可以
	}, function(res) {
		if (onUploadError) {
			onUploadError("获取上传token错误");
		}
	}, function(xhr) {
		if (onUploadError) {
			onUploadError("获取上传token错误");
		}
	});

}
